import 'package:get/get.dart';
import 'package:kkhousekeep/config/constant.dart';
import 'package:kkhousekeep/net/home_bill_connect.dart';

import '../../../../models/home_bill_list_entity.dart';
import 'bill_details_page.dart';

class BillPageController extends GetxController {
  static const String unitYear = '年';
  static const String unitMonth = '月';

  var years = <String>[];
  var yearIndex = 0.obs;

  var yearsBillMaps = <String, List<HomeBillListObj>>{}.obs;

  late BillConnect _connect;

  @override
  void onInit() {
    _connect = Get.put(BillConnect());
    int year = DateTime.now().year;
    years = [year.toString()];
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    _loadNetworkData();
  }

  List<HomeBillListObj> getCurrentBillList() {
    var year = years[yearIndex.value];
    return yearsBillMaps[year] ?? [];
  }

  void performClickDialogConfirm(int newIndex) {
    yearIndex.value = newIndex;
    _loadYearsData();
  }

  Future _loadNetworkData() async {
    var billYears = await _connect.getBillYears();
    if (billYears.isNotEmpty) {
      years = billYears;
    }
    yearIndex.value = years.length - 1;
    await _loadYearsData();
  }

  Future _loadYearsData() async {
    var year = years[yearIndex.value];
    if (!yearsBillMaps.containsKey(year) || (yearsBillMaps[year]!.isEmpty)) {
      _connect
          .getBillList(year: year.replaceAll(unitYear, ''))
          .then((value) => yearsBillMaps[year] = value);
    }
  }

  void performClickItem(HomeBillListObj entity) {
    var year = years[yearIndex.value].replaceAll(unitYear, '');
    var arguments = {
      ArgumentKey.year: int.parse(year),
      ArgumentKey.month: entity.month,
    };
    Get.to(() => const BillDetailsPage(), arguments: arguments);
  }
}
